package com.zadtek.shopmall.fragments;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.TableLayout;

import com.zadtek.shopmall.R;
import com.zadtek.shopmall.base.AbsFragment;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by zack on 2018/5/31.
 */

public class TabFragment extends AbsFragment {
    private TabLayout tabLayout;
    private List<Fragment> fragments = new LinkedList<>();
    private FragmentManager fragmentManager;
    private Fragment mFragmentContent;

    @Override
    public int setView() {
        return R.layout.fragment_tab;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initData();
        initView();
        initLogic();
    }

    private void initLogic() {
        setDefaultFragment(fragments.get(0));
    }

    private void initData() {
        fragmentManager = getChildFragmentManager();
        fragments.add(new CarFragment());
        fragments.add(new NearbyFragment());
    }

    private void initView() {
        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switchFragment(fragments.get(tab.getPosition()));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    private void setDefaultFragment(Fragment fragment){
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.container,fragments.get(0)).commit();
        mFragmentContent = fragments.get(0);
    }

    private void switchFragment(Fragment fragment){
        if (mFragmentContent!=fragment) {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.container,fragment).commit();
            mFragmentContent = fragment;
        }
    }
}
